<!--
 * @Description: 编辑分账账户
 * @Author: DXV-RGWU-TUFH-RFCY-IEGMYY
 * @Date: 2023-08-11 16:13:58
 * @LastEditTime: 2023-08-31 15:58:15
 * @LastEditors: DXV-RGWU-TUFH-RFCY-IEGMYY
-->

<template>
  <div class="lb-adapay-list-edit">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <el-form
        @submit.native.prevent
        :model="subForm"
        ref="subForm"
        :rules="subFormRules"
        label-width="170px"
      >
        <el-form-item label="结算账户类型" prop="is_company">
          <el-radio-group
            :disabled="subForm.mid ? true : false"
            @change="changeCompanyType"
            v-model="subForm.is_company"
          >
            <el-radio :label="1">个体户/企业</el-radio>
            <el-radio :label="2">个人</el-radio>
          </el-radio-group>
          <lb-tool-tips
            >对私分账，账户绑定无需审核；对公分账，需添加企业信息到三方审核</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="关联用户" prop="user_id">
          <el-tag
            class="cursor-pointer"
            :type="subForm.user_id ? 'primary' : 'danger'"
            @click="toShowDialog('user')"
            >{{ subForm.user_id ? subForm.nickName : '选择关联用户' }}</el-tag
          >
        </el-form-item>
        <block v-if="subForm.is_company === 1">
          <lb-classify-title title="商家信息"></lb-classify-title>
          <el-form-item label="商户名称" prop="name">
            <el-input
              v-model="subForm.name"
              placeholder="请输入商户名称"
            ></el-input>
            <lb-tool-tips>请输入营业执照上的名称</lb-tool-tips>
          </el-form-item>
          <el-form-item label="所在区域" prop="area">
            <el-cascader
              size="large"
              :options="areaOptions"
              v-model="subForm.area"
              @change="handleChange"
              placeholder="请选择省市区"
              :props="{
                checkStrictly: true,
                label: 'title',
                children: 'cities'
              }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="social_credit_code">
            <el-input
              v-model="subForm.social_credit_code"
              placeholder="请输入统一社会信用代码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="统一社会信用证有效期"
            prop="social_credit_code_expires"
          >
            <div class="flex-y-center">
              <el-date-picker
                v-model="subForm.social_credit_code_expires"
                type="date"
                :editable="false"
                :clearable="false"
                placeholder="请选择日期"
                value-format="yyyyMMdd"
              ></el-date-picker>
              <div class="f-desc c-warning ml-md">
                永久执照请选择2099年12月31日
              </div>
            </div>
          </el-form-item>
          <el-form-item label="经营范围" prop="business_scope">
            <el-input
              v-model="subForm.business_scope"
              placeholder="请输入经营范围"
            ></el-input>
            <lb-tool-tips>请输入营业执照上的经营范围</lb-tool-tips>
          </el-form-item>
          <el-form-item label="法人姓名" prop="legal_person">
            <el-input
              v-model="subForm.legal_person"
              placeholder="请输入法人姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="法人手机号" prop="legal_mp">
            <el-input
              v-model="subForm.legal_mp"
              placeholder="请输入法人手机号"
            ></el-input>
          </el-form-item>
          <el-form-item label="法人身份证号" prop="legal_cert_id">
            <el-input
              v-model="subForm.legal_cert_id"
              placeholder="请输入法人身份证号"
            ></el-input>
          </el-form-item>
          <el-form-item label="法人身份证有效期至" prop="legal_cert_id_expires">
            <el-date-picker
              v-model="subForm.legal_cert_id_expires"
              type="date"
              placeholder="请选择日期"
              value-format="yyyyMMdd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="企业地址" prop="address">
            <el-input
              v-model="subForm.address"
              placeholder="请输入企业地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="attach_file">
            <div class="flex-warp">
              <div class="lb-file-input flex-between">
                <div :class="[{ 'c-title': subForm.attach_file }]">
                  {{ subForm.attach_file | handleFileName }}
                </div>
                <div class="flex-center">
                  <i
                    @click="toResetFile('attach_file')"
                    class="c-warning iconfont icon-guanbi-fill pl-sm pr-sm"
                    v-if="subForm.attach_file"
                  ></i>

                  <lb-button
                    v-loading="uploadLoading"
                    size="mini"
                    type="primary"
                    @click="handleBtnUplaod('attach_file')"
                    >{{ $t('action.upload') }}</lb-button
                  >
                </div>
              </div>
              <lb-tool-tips>
                内容须包含三证合一证件照、法人身份证正面照、法人身份证反面照、开户银行许可证照压缩zip包后上传
                <div class="mt-sm">附件仅支持zip格式</div>
              </lb-tool-tips>
            </div>
          </el-form-item>
        </block>
        <lb-classify-title title="结算信息"></lb-classify-title>
        <el-form-item
          label="银行账户类型"
          prop="bank_acct_type"
          v-if="subForm.is_company === 1"
        >
          <el-radio-group
            :disabled="subForm.mid ? true : false"
            v-model="subForm.bank_acct_type"
          >
            <el-radio :label="1">对公</el-radio>
            <el-radio :label="2">对私</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="结算账户银行卡号" prop="card_id">
          <el-input
            v-model="subForm.card_id"
            placeholder="请输入结算账户银行卡号"
          ></el-input>
          <lb-tool-tips>分成佣金到账银行卡卡号</lb-tool-tips>
        </el-form-item>
        <el-form-item label="开户银行名称" prop="bank_name">
          <el-input
            v-model="subForm.bank_name"
            placeholder="请输入开户银行名称"
          ></el-input>
          <lb-tool-tips>例如：中国农业银行总府支行</lb-tool-tips>
        </el-form-item>
        <block v-if="subForm.bank_acct_type === 1">
          <el-form-item label="开户银行所在地" prop="bank_area">
            <el-cascader
              size="large"
              :options="areaOptions"
              v-model="subForm.bank_area"
              @change="handleChange"
              placeholder="请选择省市区"
              :props="{
                checkStrictly: true,
                label: 'title',
                children: 'cities'
              }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="银行编码" prop="bank_code">
            <el-input
              v-model="subForm.bank_code"
              placeholder="请输入银行编码"
            ></el-input>
            <lb-tool-tips>
              <a
                class="c-link cursor-pointer"
                href="https://docs.adapay.tech/api/appendix.html#bank-code"
                target="_blank"
                >具体编码请点击查看</a
              >
            </lb-tool-tips>
          </el-form-item>
        </block>
        <el-form-item label="银行卡户名" prop="card_name">
          <el-input
            :disabled="subForm.mid ? true : false"
            v-model="subForm.card_name"
            placeholder="请输入银行卡户名"
          ></el-input>
          <lb-tool-tips>例如：银行卡绑定的用户姓名</lb-tool-tips>
        </el-form-item>

        <block v-if="subForm.bank_acct_type === 2">
          <el-form-item label="身份证号" prop="cert_id">
            <el-input
              :disabled="subForm.mid ? true : false"
              v-model="subForm.cert_id"
              placeholder="请输入身份证号"
            ></el-input>
            <lb-tool-tips>例如：银行卡开户的身份证号</lb-tool-tips>
          </el-form-item>
        </block>
        <el-form-item label="手机号" prop="tel_no">
          <el-input
            v-model="subForm.tel_no"
            placeholder="请输入手机号"
          ></el-input>
          <lb-tool-tips>例如：银行卡开户预留的手机号</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button
            type="primary"
            @click="submitFormInfo('sub')"
            v-preventReClick
            >{{ $t('action.submit') }}</lb-button
          >
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <el-dialog
        title="关联用户"
        :visible.sync="showDialog.user"
        width="800px"
        center
      >
        <lb-tips v-if="routesItem.userInfo.is_admin === 0"
          >请输入用户昵称/手机号后点击查询数据</lb-tips
        >
        <el-form
          :inline="true"
          :model="searchForm.user"
          ref="userForm"
          label-width="70px"
          class="dialog-form"
        >
          <el-form-item label="输入查询" prop="phone">
            <el-input
              v-model="searchForm.user.phone"
              placeholder="请输入用户昵称/手机号"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <lb-button
              size="medium"
              type="primary"
              icon="el-icon-search"
              style="margin-right: 5px"
              @click="getTableDataList(1, 'user')"
              >{{ $t('action.search') }}</lb-button
            >
            <lb-button
              size="medium"
              icon="el-icon-refresh-left"
              style="margin-right: 5px"
              @click="resetForm('user')"
              >{{ $t('action.reset') }}</lb-button
            >
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading.user"
          :data="tableData.user"
          ref="singleTable"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          tooltip-effect="dark"
          style="width: 100%"
          highlight-current-row
          @current-change="handleSelectionChange"
        >
          <el-table-column prop="id" label="用户ID"></el-table-column>
          <el-table-column prop="avatarUrl" label="头像">
            <template slot-scope="scope">
              <lb-image :src="scope.row.avatarUrl" />
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
        </el-table>
        <lb-page
          :batch="false"
          :page="searchForm.user.page"
          :pageSize="searchForm.user.limit"
          :total="total.user"
          @handleSizeChange="handleSizeChange($event, 'user')"
          @handleCurrentChange="handleCurrentChange($event, 'user')"
        >
        </lb-page>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showDialog.user = false">取 消</el-button>
          <el-button
            type="primary"
            @click="handleDialogConfirm"
            v-preventReClick
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
    <input
      type="file"
      accept="text"
      style="display: none"
      @change="uploadFiles"
      ref="inputFile"
    />
  </div>
</template>

<script>
import moment from 'moment'
import { mapState } from 'vuex'
import provinceAndCityData from '@/utils/adapay.json'
export default {
  data () {
    return {
      navTitle: '',
      areaOptions: provinceAndCityData,
      member_info: ['is_company', 'user_id', 'member_id', 'order_no', 'name', 'social_credit_code', 'social_credit_code_expires', 'business_scope', 'legal_person', 'legal_cert_id', 'legal_cert_id_expires', 'legal_mp', 'address', 'attach_file'],
      bank_info: ['member_id', 'settle_account_id', 'bank_acct_type', 'card_id', 'card_name', 'cert_id', 'tel_no', 'bank_code', 'bank_name'],
      subForm: {
        mid: '',
        bid: '',
        is_company: 1,
        user_id: '',
        nickName: '',
        member_id: '',
        order_no: '',
        settle_account_id: '',
        // 商家信息
        name: '',
        social_credit_code: '',
        social_credit_code_expires: '',
        business_scope: '',
        legal_person: '',
        legal_cert_id: '',
        legal_cert_id_expires: '',
        legal_mp: '',
        address: '',
        attach_file: '',
        area: [],
        // 结算信息
        card_id: '',
        card_name: '',
        cert_id: '',
        tel_no: '',
        bank_code: '',
        bank_name: '',
        bank_acct_type: 1,
        bank_area: []
        // prov_code: '',
        // area_code: ''
      },
      subFormRules: {
        is_company: { required: true, type: 'number', message: '请选择结算账户类型', trigger: 'blur' },
        user_id: { required: true, type: 'number', message: '请选择关联用户', trigger: 'blur' },
        name: { required: true, validator: this.$reg.isNotNull, text: '商户名称', reg_type: 2, trigger: 'blur' },
        social_credit_code: { required: true, validator: this.$reg.isNotNull, text: '统一社会信用代码', reg_type: 2, trigger: 'blur' },
        social_credit_code_expires: { required: true, type: 'string', message: '请选择统一社会信用证有效期', trigger: 'blur' },
        business_scope: { required: true, validator: this.$reg.isNotNull, text: '经营范围', reg_type: 2, trigger: 'blur' },
        legal_person: { required: true, validator: this.$reg.isNotNull, text: '法人名称', reg_type: 2, trigger: 'blur' },
        legal_cert_id: { required: true, validator: this.$reg.isIdCard, text: '法人身份证号', reg_type: 2, trigger: 'blur' },
        legal_cert_id_expires: { required: true, type: 'string', message: '请选择法人身份证有效期', trigger: 'blur' },
        legal_mp: { required: true, validator: this.$reg.isTel, text: '法人手机号', reg_type: 2, trigger: 'blur' },
        address: { required: true, validator: this.$reg.isNotNull, text: '企业地址', reg_type: 2, trigger: 'blur' },
        attach_file: { required: true, type: 'string', message: '请上传附件', trigger: 'blur' },
        area: { required: true, type: 'array', message: '请选择省市区', trigger: 'blur' },
        bank_acct_type: { required: true, type: 'number', message: '请选择银行账户类型', trigger: 'blur' },
        card_id: { required: true, validator: this.$reg.isNotNull, text: '结算账户银行卡号', reg_type: 2, trigger: 'blur' },
        card_name: { required: true, validator: this.$reg.isNotNull, text: '银行卡户名', reg_type: 2, trigger: 'blur' },
        cert_id: { required: true, validator: this.$reg.isIdCard, text: '身份证号', reg_type: 2, trigger: 'blur' },
        tel_no: { required: true, validator: this.$reg.isTel, text: '手机号', reg_type: 2, trigger: 'blur' },
        bank_code: { required: true, validator: this.$reg.isNotNull, text: '银行编码', reg_type: 2, trigger: 'blur' },
        bank_area: { required: true, type: 'array', message: '请选择省市区', trigger: 'blur' }
      },
      loading: { user: false },
      searchForm: {
        user: {
          page: 1,
          limit: 10,
          phone: ''
        }
      },
      tableData: { user: [] },
      total: { user: 0 },
      showDialog: { user: false },
      currentRow: {},
      uploadLoading: false,
      fileName: '',
      lockTap: false
    }
  },
  async created () {
    let { id } = this.$route.query
    if (id) {
      this.subForm.mid = id
      this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.AdapayListEdit' : 'menu.AdapayListAdd')
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    /**
     * @name: 详情
     * @param {*} id
     */
    async getDetail (id) {
      let { code, data } = await this.$api.adapay.memberInfo({ id })
      if (code !== 200) return
      let { is_company: company } = data.member_info
      let { bank_acct_type: batype } = data.bank_info
      let area = []
      let barea = []
      if (company === 1) {
        let { prov_code: pcode, area_code: acode } = data.member_info
        area = [pcode, acode]
      }
      if (batype === 1) {
        let { prov_code: bpcode, area_code: bacode } = data.bank_info
        barea = [bpcode, bacode]
      }
      let params = Object.assign({}, data.member_info, data.bank_info)
      params.area = area
      params.bank_area = barea
      params.mid = data.member_info.id
      params.bid = data.bank_info.id
      for (let i in this.subForm) {
        this.subForm[i] = params[i]
      }
    },
    handleBtnUplaod (name) {
      this.fileName = name
      this.$refs['inputFile'].click()
    },
    uploadFiles (e) {
      let file = e.target.files[0]
      let { name } = file
      if (name.indexOf('zip') < 0) {
        this.$message.error('请上传zip格式的文件夹')
      } else {
        let formData = new FormData()
        formData.append('file[]', file)
        formData.append('type', 'cert')
        if (this.uploadLoading) return
        this.uploadLoading = true
        try {
          this.$api.upload.uploadFiles(formData).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successUpload'))
              this.subForm[this.fileName] = res.data[0].attachment_path
              this.uploadLoading = false
            }
          })
        } catch (e) {
          this.uploadLoading = false
        }
      }
    },
    getFile (file, key) {
      let len = file.length - 1
      this.subForm[key] = file[len].url
    },
    toResetFile (key) {
      this.subForm[key] = ''
    },
    changeCompanyType (e) {
      this.subForm.bank_acct_type = e
    },
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.loading[key] = true
      let searchForm = JSON.parse(JSON.stringify(this.searchForm[key]))
      let methodArr = {
        user: { methodKey: 'custom', methodModel: 'userSelectByPhone' }
      }
      let { methodKey, methodModel } = methodArr[key]
      let { code, data } = await this.$api[methodKey][methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    async toShowDialog (key) {
      this.currentRow = {}
      this.searchForm.user.phone = ''
      await this.getTableDataList(1, key)
      this.showDialog[key] = !this.showDialog[key]
    },
    handleSelectionChange (val) {
      val = JSON.parse(JSON.stringify(val))
      let { id, nickName } = val
      val.nickName = nickName || `用户ID ${id}`
      this.currentRow = val
    },
    handleDialogConfirm () {
      if (this.currentRow === null || !this.currentRow.id) {
        this.$message.error(`请选择用户`)
        return
      }
      let { id = 0, nickName = '' } = this.currentRow
      this.subForm.user_id = id
      this.subForm.nickName = nickName
      this.showDialog.user = false
    },
    /**
     * @name: 新增/编辑
     * @param {*}
     */
    async submitFormInfo (key) {
      let flag = true
      this.$refs[`${key}Form`].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this[`${key}Form`]))
        let { mid = 0, bid, is_company: company, area, bank_area: barea, bank_acct_type: batype } = subForm
        if ((company === 1 && area.length < 2) || (batype === 1 && barea.length < 2)) {
          let msg = area.length < 2 ? `所在区域` : `开户银行所在地`
          this.$message.error(`${msg} 请选择具体的省市区`)
          return
        }
        if (company === 1 && !/\.(zip)$/.test(subForm.attach_file)) {
          this.$message.error(`附件仅支持zip格式!`)
          return
        }
        if (this.lockTap) return
        this.lockTap = true
        let modelMethod = mid ? 'memberUpdate' : 'memberAdd'
        let member = this.$util.pick(subForm, company === 1 ? this.member_info : ['is_company', 'user_id', 'member_id'])
        let bank = this.$util.pick(subForm, this.bank_info)
        if (company === 1) {
          member.prov_code = area[0]
          member.area_code = area[1]
        }
        member.id = mid
        bank.prov_code = batype === 1 ? barea[0] : ''
        bank.area_code = batype === 1 ? barea[1] : ''
        bank.id = bid
        let { code } = await this.$api.adapay[modelMethod]({ id: mid, member_info: member, bank_info: bank })
        if (code !== 200) {
          this.lockTap = false
          return
        }
        this.$message.success(this.$t(mid ? 'tips.successRev' : 'tips.successSub'))
        this.$router.back(-1)
      }
    }
  },
  filters: {
    handleFileName (url) {
      let text = '请上传附件'
      if (url) {
        text = url.substring(url.lastIndexOf('/') + 1)
      }
      return text
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-adapay-list-edit {
  width: 100%;
  .el-form {
    width: 100%;
    .el-select,
    .el-input-number,
    .el-input,
    .el-cascader {
      width: 300px;
    }
    .el-textarea {
      width: 600px;
    }
  }
}
</style>
